//
//  ChangeMobileViewController.m
//  HuaMuJinRong
//
//  Created by 吴建东 on 16/4/18.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "ChangeMobileViewController.h"
#import "NSString+Shove.h"

@interface ChangeMobileViewController ()<HTTPClientDelegate>
@property (weak, nonatomic) IBOutlet UILabel *mobileNumValue;
@property (weak, nonatomic) IBOutlet UITextField *mobileTextField;
@property (weak, nonatomic) IBOutlet UIView *mobileBackView;
@property (weak, nonatomic) IBOutlet UIView *codeBackView;
@property (weak, nonatomic) IBOutlet UILabel *verifyNumValue;
@property (weak, nonatomic) IBOutlet UITextField *verifyNumTextField;
@property (weak, nonatomic) IBOutlet UIButton *verifyButton;
@property (weak, nonatomic) IBOutlet ClickButton *sureButton;
@property (weak, nonatomic) IBOutlet UIButton *questionButton;

@property (nonatomic, strong) NetWorkClient *requestClient;
@property (nonatomic, assign) BOOL          isLoading;
@property (nonatomic, assign) NSInteger     requestType;
@end

@implementation ChangeMobileViewController
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    if (_requestClient != nil) {
        [_requestClient cancel];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.edgesForExtendedLayout = UIRectEdgeNone;

    if (_naviTitle.length > 0) {
        [self initNavBarTitle:_naviTitle andLeftItemName:@"返回" andRightItemName:@""];
    }else {
        if (!_isChangeBank) {
            [self initNavBarTitle:@"更换手机号" andLeftItemName:@"返回" andRightItemName:@""];
        }else {
            [self initNavBarTitle:@"更改预留手机号" andLeftItemName:@"返回" andRightItemName:@""];
        }
    }
    
    _sureButton.clipsToBounds = YES;
    _sureButton.layer.cornerRadius = kCornerRadius;
    _sureButton.titleLabel.font = KFontSize(15.0);
    _questionButton.titleLabel.font = KFontSize(13.0);
    _mobileNumValue.font = KFontSize(15.0);
    _verifyNumValue.font = KFontSize(15.0);
    _verifyButton.titleLabel.font = KFontSize(13.0);
    _verifyNumTextField.font = KFontSize(14.0);
    _mobileTextField.font = KFontSize(14.0);
    
    [CommonClass buttonEnableWithButton:_sureButton enable:NO];
    [_mobileTextField addTarget:self action:@selector(changeValue) forControlEvents:UIControlEventEditingChanged];
    [_verifyNumTextField addTarget:self action:@selector(changeValue) forControlEvents:UIControlEventEditingChanged];
    
    
}

- (void)changeValue {
    if (_mobileTextField.text.length>0 && _verifyNumTextField.text.length>0) {
        [CommonClass buttonEnableWithButton:_sureButton enable:YES];
    }else {
        [CommonClass buttonEnableWithButton:_sureButton enable:NO];
    }
}

- (IBAction)verifyButtonClick:(id)sender {
    if (_mobileTextField.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    if (![_mobileTextField.text isPhone]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return;
    }
    
    [self getVerifyCodeRequest];
}

- (IBAction)sureButtonClick:(id)sender {
    if (_mobileTextField.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入手机号"];
        return;
    }
    if (![_mobileTextField.text isPhone]) {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号"];
        return;
    }
    if (_verifyNumTextField.text.length <= 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        return;
    }
    
    [self changeRequest];
}

- (IBAction)questionButtonClick:(id)sender {
}

- (void)timeDown {
    __block NSInteger timeout = 60; //倒计时时间
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){ //倒计时结束，关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                [_verifyButton setTitle:@"发送验证码" forState:UIControlStateNormal];
                _verifyButton.enabled = YES;
            });
        }else{
            int seconds = timeout % 61;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                
                [_verifyButton setTitle:[NSString stringWithFormat:@" (%@) ",strTime] forState:UIControlStateNormal];
                _verifyButton.enabled = NO;
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}

#pragma mark - 请求数据
- (void)initData {
    
    [self getVerifyCodeRequest];
}

- (void)changeRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求，请稍候再试..."];
        return;
    }
    _requestType = 2;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    if (self.isChangeBank) {
        [parameters setObject:@"604" forKey:@"OPT"];
    }else {
        [parameters setObject:@"7" forKey:@"OPT"];
    }
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:AppDelegateInstance.userInfo.userId forKey:@"id"];
    [parameters setObject:_mobileTextField.text forKey:@"cellPhone"];
    [parameters setObject:_verifyNumTextField.text forKey:@"randomCode"];
    
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
        
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

- (void)getVerifyCodeRequest {
    if (_isLoading) {
        [SVProgressHUD showImage:nil status:@"正在请求，请稍候再试..."];
        return;
    }
    _requestType = 1;
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setObject:@"4" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:_mobileTextField.text forKey:@"cellPhone"];
    [parameters setObject:@"2" forKey:@"type"];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
        
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

#pragma - 网络数据回调代理
- (void)startRequest {
    _isLoading = YES;
    if (_requestType == 2) {
        _mobileTextField.userInteractionEnabled = NO;
    }
}

// 返回成功
- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
    _isLoading = NO;
    NSDictionary *dics = obj;
    // DLOG(@"dic=%@",dics);
    if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        if (_requestType == 1) {
            [SVProgressHUD showSuccessWithStatus:[dics objectForKey:@"msg"]];
            
            [self timeDown];
        }else if (_requestType == 2) {
            [SVProgressHUD showSuccessWithStatus:[dics objectForKey:@"msg"]];
            
            if (_isChangeBank == NO) {
                AppDelegateInstance.userInfo.isMobileStatus = YES;
                AppDelegateInstance.userInfo.mobile = _mobileTextField.text;
            }
            if (_backNum > 0) {
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - _backNum] animated:YES];
            }else {
                [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count - 3] animated:YES];
            }
            
        }
        
        
    }else if ([[NSString stringWithFormat:@"%@",[dics objectForKey:@"error"]] isEqualToString:@"-2"]) {
        
        [ReLogin outTheTimeRelogin:self];
    }else {

        [SVProgressHUD showImage:nil status:[dics objectForKey:@"msg"]];
    }
    
}

// 返回失败
- (void)httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error {
    if (_requestType == 2) {
        _mobileTextField.userInteractionEnabled = YES;
    }
}

// 无可用的网络
- (void)networkError {
    //  [SVProgressHUD showErrorWithStatus:@"网络不给力，请检查您的网络设置"];
    if (_requestType == 2) {
        _mobileTextField.userInteractionEnabled = YES;
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
